package org.jlambda.list;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class NonMemoizingList<T> extends List<T> implements Iterable<T> {

	public NonMemoizingList(ListDeclaration<T> de){
		super(de);
	}

	public Iterator<T> iterator() {
		return new AllwaysItr();
	}
	
	class AllwaysItr implements Iterator<T> {
		boolean nexted = true; // have to start it off in case of no elements
		T object = null;
		boolean eold = false;
		
		ListDeclaration<T> idecl;
		
		AllwaysItr(){
			idecl = getDecl().copyDeclaration(NonMemoizingList.this);
		}
		
		T getNext(){
			object = idecl.getNext();
			eold = idecl.isEOL();
			return object;
		}
		
		public boolean hasNext() {
			if (eold) return false;
			
			if (!nexted) return true;
			
			object = getNext();
			nexted = false;
			return !eold;
		}

		public T next() {
			if (eold) throw new NoSuchElementException("List has no more items");
			
			T ob = null;
			
			if (nexted) {
				// called next again without hasNext 
				ob = getNext();
			} else {
				// already got it 
				ob = object;
			}
			if (eold) {
				throw new NoSuchElementException("List has no more items");
			}			
			nexted = true;
				
			return ob;
		}

		public void remove() {
			
		}
	}

}
